﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

using RoverStudio.Common.WorldModel;
using RoverStudio.Math;

namespace RoverStudio.MapDisplay.WM2D
{
    public partial class MapDisplayer2D : Control
    {
        private Vector2D origin;

        /// <summary>
        /// Gets and sets the origin of the map in screen coordinates.
        /// </summary>
        public Vector2D Origin
        {
            get { return origin; }
            set { origin = value; }
        }

        private double scale;

        public new double Scale
        {
            get { return scale; }
            set { scale = value; }
        }

        //private double rotation;

        //public double Rotation
        //{
        //    get { return rotation; }
        //    set
        //    {
        //        while (value > System.Math.PI)
        //        {
        //            value -= 2 * System.Math.PI;
        //        }
        //        while (value < -System.Math.PI)
        //        {
        //            value += 2 * System.Math.PI;
        //        }
        //        rotation = value;
        //    }
        //}

        private WorldModel worldModel;

        public WorldModel WorldModel
        {
            get { return worldModel; }
            set { worldModel = value; }
        }


        public MapDisplayer2D()
        {
            InitializeComponent();
        }

        protected override void OnPaint(PaintEventArgs pe)
        {
            if (worldModel == null)
            {
                base.OnPaint(pe);
                return;
            }

            Graphics gr = pe.Graphics;

            foreach (PhysicalObject obj in worldModel.GetPhysicalObjects())
            {
                Vector2D topLeft = TransformWorldToDisplay(obj.Position + obj.Diameter.FlipVertical());
                Vector2D topRight = TransformWorldToDisplay(obj.Position + obj.Diameter);
                Vector2D bottomLeft = TransformWorldToDisplay(obj.Position - obj.Diameter);
                Vector2D bottomRight = TransformWorldToDisplay(obj.Position + obj.Diameter.FlipHorizontal());

                gr.DrawRectangle(Pens.Black, new Rectangle((int)topLeft.X, (int)topLeft.Y, (int)(topLeft - bottomRight).X, (int)(topLeft - bottomRight).Y));
            }
            base.OnPaint(pe);
        }

        public Vector2D TransformWorldToDisplay(Vector3D vector)
        {
            Vector2D projection = (Vector2D)vector;
            Vector2D display = projection.Shift(-origin).Scale(scale);
            return display;
        }
    }
}
